package org.qianji.goosql.dql.clause;

import java.util.List;
import java.util.Map;

import org.qianji.goosql.cond.And;
import org.qianji.goosql.cond.Condition;
import org.qianji.goosql.cond.Conditions;
import org.qianji.goosql.cond.Or;

/**
 * 简单Where子句。
 * 
 * @author gmz
 * 
 */
public class SimpleWhere implements Where {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4991706650030921109L;

	private Condition cond;

	/**
	 * 默认构造子。
	 */
	public SimpleWhere() {
		super();
	}

	/**
	 * 根据查询条件构造简单Where子句，所有条件都以AND连接。
	 * 
	 * @param conds
	 *            {@link Condition} 查询条件数组
	 */
	public SimpleWhere(Condition... conds) {
		super();
		if (conds != null) {
			this.cond = Conditions.and(conds);
		}
	}

	@Override
	public boolean hasConds() {
		return (cond != null ? true : false);
	}

	@Override
	public Condition getCond() {
		return cond;
	}

	@Override
	public Where setCond(Condition cond) {
		if (cond == null) {
			throw new NullPointerException("cond can't be null");
		}
		this.cond = cond;
		return this;
	}

	@Override
	public Where and(Condition cond) {
		if (cond == null) {
			throw new NullPointerException("cond can't be null");
		}
		this.cond = (this.cond != null ? new And(this.cond, cond) : cond);
		return this;
	}

	@Override
	public Where or(Condition cond) {
		if (cond == null) {
			throw new NullPointerException("cond can't be null");
		}
		this.cond = (this.cond != null ? new Or(this.cond, cond) : cond);
		return this;
	}

	@Override
	public String toSql() {
		StringBuffer wh = new StringBuffer();
		if (this.hasConds()) {
			wh.append("WHERE ").append(cond.toSql());
		}
		return wh.toString();
	}

	@Override
	public List<Object> getPlacedParameters() {
		return cond.getPlacedParameters();
	}

	@Override
	public Map<String, Object> getNamedParameters() {
		return cond.getNamedParameters();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null || !(obj instanceof SimpleWhere)) {
			return false;
		}
		SimpleWhere other = (SimpleWhere) obj;
		if (cond.equals(other.getCond())) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int hc = 37 * 17 + cond.hashCode();
		return hc;
	}

	@Override
	public String toString() {
		return toSql();
	}

}
